package com.spzx.order.receiver;

import com.rabbitmq.client.Channel;
import com.spzx.common.rabbit.constant.MqConst;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * @author: atguigu
 * @create: 2025-02-28 09:20
 */
@Slf4j
@Component
public class TestReceiver {


    /**
     * 接收测试队列消息
     * 没有特殊指定确认模式：默认自动 监听器没有异常，自动ack,如果有异常自动nack将消息重新入队
     *
     * @param message
     */
    @RabbitListener(
            bindings = @QueueBinding(
                    exchange = @Exchange(value = MqConst.EXCHANGE_TEST, durable = "true"),
                    value = @Queue(value = MqConst.QUEUE_TEST, durable = "true"),
                    key = MqConst.ROUTING_TEST
            )
    )
    public void reiceve(String message) {
        log.info("接收到消息：{}", message);
    }


    @SneakyThrows
    @RabbitListener(
            bindings = @QueueBinding(
                    exchange = @Exchange(value = MqConst.EXCHANGE_TEST, durable = "true"),
                    value = @Queue(value = MqConst.QUEUE_CONFIRM, durable = "true"),
                    key = MqConst.ROUTING_CONFIRM
            )
    )
    public void receiveConfirm(String data, Message message, Channel channel) {
        try {
            log.info("接收到消息：{}，业务逻辑执行..", data);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.error("消息消费失败：{}", e.getMessage());
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
        }
    }
}
